package luj.tool.jnproxyan.proxy.network.socks.actor.root.message.admin.rule.list;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import luj.tool.jnproxyan.proxy.admin.http.render.TimeValueRenderer;
import luj.tool.jnproxyan.proxy.admin.http.render.ValueDefaultRenderer;
import luj.tool.jnproxyan.proxy.rule.ConnectRules;
import luj.tool.jnproxyan.proxy.rule.RuleItem;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.Socks5Actor;
import luj.tool.jnproxyan.proxy.util.data.wrap.DataResultWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
final class OnRuleList implements Socks5Actor.Handler<RuleListMsg> {

  @Override
  public void onHandle(Context ctx) throws Exception {
    Socks5Actor self = ctx.getActorState(this);
    RuleListMsg msg = ctx.getMessage(this);

    ConnectRules rule = _wrapper.wrap(self.getConnectRule());
    List<?> itemList = rule.itemMap().values().stream()
        .map(this::makeRow)
        .collect(Collectors.toList());

    Map<String, ?> table = ImmutableMap.of(
        "header", ImmutableList.of("地址", "添加时间"),
        "body", itemList
    );

    msg.http().responsePage(ImmutableMap.of(
        "table", table
    ));
  }

  private Map<String, ?> makeRow(RuleItem item) {
    return ImmutableMap.of(
        "data", renderItem(item)
    );
  }

  private List<String> renderItem(RuleItem item) {
    String pattern = item.targetHost().get();
    String addTime = new TimeValueRenderer().render(item.createTime().get());

    return Stream.of(pattern, addTime)
        .map(s -> new ValueDefaultRenderer(s).render())
        .collect(Collectors.toList());
  }

  @Autowired
  DataResultWrapper _wrapper;
}
